    //
//  ModuleTesterViewController.m
//  LecturePad
//
//  Created by vo loc on 12/25/10.
//  Copyright 2010 Epsilon Mobile. All rights reserved.
//

#import "ModuleTesterViewController.h"
#import "MultipleViewControllerTester.h"
#import "ModulesKeyDefines.h"
#import "ModuleInfo.h"
#import "ModuleTester.h"

#define kTestListFile	@"ModuleList"

@interface ModuleTesterViewController ( Logical )
- (void)retrieveModuleList;
- (BOOL)isClassExists:(NSString *)className;
- (NSString*)findTesterClassName:(NSDictionary *)moduleInfo;
- (void)runViewControllerTest:(Class)testerClass;
- (void)loadModule:(NSDictionary*)moduleInfo;
@end

@implementation ModuleTesterViewController

- (void)viewDidLoad {
  [super viewDidLoad];
  
  [self retrieveModuleList];
  
  [_tableView reloadData];
}

- (void)viewDidUnload {
  [super viewDidUnload];

  [_moduleList release];
}

- (IBAction)runAllUnitTestSuites:(id)sender
{
 	 
}

- (void)close:(id)sender
{
  if( [self.modalViewController respondsToSelector:@selector(saveSettings)] )
  {
   	[self.modalViewController performSelector:@selector(saveSettings)]; 
  }
  
  [self dismissModalViewControllerAnimated:YES];
  
  [sender removeFromSuperview];
}

#pragma mark UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
  [self loadModule:[_moduleList objectAtIndex:indexPath.row]];
}

#pragma mark UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
  return [_moduleList count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
  static NSString* CellIdentifier = @"Cell";
	UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
  if( cell == nil )
  {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
  }
  
  // TODO: icon for each test file
  // TODO: highlight if test class not exists
  ModuleInfo* module = [_moduleList objectAtIndex:indexPath.row];
  
  cell.textLabel.text = [module name];
  cell.detailTextLabel.text = [module description];
  
  return cell;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Overriden to allow any orientation.
    return YES;
}

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc. that aren't in use.
}

- (void)dealloc {
    [super dealloc];
}


@end

@implementation ModuleTesterViewController (Logical)

- (void)retrieveModuleList
{
 	// retrieve module list from ModuleList.plist
  NSString* path = [[NSBundle mainBundle] pathForResource:kTestListFile ofType:@"plist"];
  NSArray* list = [NSArray arrayWithContentsOfFile:path];
  
  // analyze list
  // for each items, find correspondance's '<ModuleName>.plist'
  _moduleList = [[NSMutableArray alloc] init];
  for( NSString* moduleName in list )
  {
    ModuleInfo* moduleInfo = [ModuleInfo moduleInfoWithName:moduleName];
    if( moduleInfo != nil )
      [_moduleList addObject:moduleInfo];
  } 
}

- (void)runViewControllerTest:(Class)testerClass
{
  // load view controller 
  UIViewController* viewController;
  
  NSString* nib = NSStringFromClass(testerClass);
  
  // check for nib file existence
  // - if there is no nib file, load using normal init
  // - if there is, use nib file to load
  if( [[NSBundle mainBundle] pathForResource:nib ofType:@"xib"] == nil )
  {
    viewController = [[testerClass alloc] init];
  }
  else {
    // always load with nib
    viewController = [[testerClass alloc] initWithNibName:NSStringFromClass(testerClass) bundle:nil];
  }
  
  [self presentModalViewController:viewController animated:YES];
  [viewController release];
  
  UIButton* btn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 60, 30)];
  [[[UIApplication sharedApplication]keyWindow] addSubview:btn];
  [btn release];
  
  btn.backgroundColor = [UIColor blackColor];
  [btn setTitle:@"Close" forState:UIControlStateNormal];
  [btn addTarget:self action:@selector(close:) forControlEvents:UIControlEventTouchUpInside];
  
  if( ![[UIApplication sharedApplication] isStatusBarHidden] )
  {
    btn.frame = CGRectMake(0, 14, 60, 30);
  }
}

- (void)loadModule:(ModuleInfo*)moduleInfo
{
  if( ![moduleInfo hasTesters] )
  {
    NSString* format = @"Can't find testers for module %@";
    NSString* message = [NSString stringWithFormat:format, moduleInfo.name];
    UIAlertView* alert = [[UIAlertView alloc] initWithTitle:message 
                                                    message:nil 
                                                   delegate:nil 
                                          cancelButtonTitle:@"Ok" 
                                          otherButtonTitles:nil];
    [alert show];
    [alert release];
    
   	return;
  }
  
  //if( [moduleInfo numberOfDemos] > 0 && [moduleInfo numberOfTestCase] == 0 )
//  {
//    // There are still many more testers, load all
//    MultipleViewControllerTester* tester = [[MultipleViewControllerTester alloc] initWithNibName:@"MultipleViewControllerTester" bundle:nil];
//    [self presentModalViewController:tester animated:YES];
//    [tester release];
//    
//    [tester loadModules:moduleInfo.dict];
//  }
//  else if( [moduleInfo numberOfTestCase] > 0 && [moduleInfo numberOfDemos] == 0 )
//  {
//    NSMutableArray* testSuites = [moduleInfo allTestsuits];
//    
//    GTMTesterViewController * gtmTester 
//    = [[GTMTesterViewController alloc] initWithNibName:@"GTMTesterViewController" 
//                                                bundle:nil];
//    [gtmTester analyzeTestSuites:testSuites];
//    gtmTester.modalPresentationStyle = UIModalPresentationFormSheet;
//    
//    [self presentModalViewController:gtmTester animated:YES];
//    [gtmTester release];
//  }
//  else 
  {
    ModuleTester* tester = [[ModuleTester alloc] initWithNibName:@"ModuleTester" bundle:nil];
    [self presentModalViewController:tester animated:YES];
    [tester release];
    
    [tester loadModule:moduleInfo];
  }
}

@end